//
//  TJTemplateDetailController.m
//  BaoDian
//
//  Created by mac on 2024/8/4.
//

#import "TJTemplateDetailController.h"
#import "SDCollectionTagsFlowLayout.h"
#import "TJTemplateTagCell.h"
#import "TJStyle1Button.h"
#import "TJVideoCoverDownloader.h"
#import "TJTemplateEditController.h"
#import "TJVideoPlayController.h"

#import "ZFAVPlayerManager.h"
#import "TJPlayerControlView.h"
#import "ZFPlayerConst.h"
#import "ZFUtilities.h"
#import "UIView+ZFFrame.h"
#import "TJUIAlertController.h"
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface TJTemplateDetailController ()<UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIImage *coverImage;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray <TJTemplateTagModel *>*tags;
@property (nonatomic, weak) UIImageView *coverImageView;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) UIImageView *containerView;
@property (nonatomic, strong) TJPlayerControlView *controlView;
@property (nonatomic, strong) UIButton *playOrPauseBtn;

@end

@implementation TJTemplateDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    CGFloat width = KScreenWidth - 32;
    
    
    UIImageView *coverImageView = [UIImageView addToView:self.view];
    coverImageView.addCornerRadius(12);
    coverImageView.userInteractionEnabled = YES;
    coverImageView.contentMode = UIViewContentModeScaleAspectFit;
    coverImageView.clipsToBounds = YES;
    [coverImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(width);
        make.centerX.offset(0);
        make.top.offset(KNavBarHight);
        make.bottom.inset(120 + TabbarSafeBottomMargin);
    }];
    
    _coverImageView = coverImageView;
    self.containerView = self.coverImageView;
    
    UIImageView *playerIconView = [UIImageView addToView:coverImageView];
    [playerIconView addTapGesturesWithTarget:self action:@selector(tapPlayerView)];
    playerIconView.image = [UIImage imageNamed:@"videoPlayer_icon"];
    [playerIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    [[TJVideoCoverDownloader shareDownLoader] downloadWithUrl:self.model.videoUrl completion:^(UIImage * _Nullable thumbnail) {
        self.coverImage = thumbnail;
        self.coverImageView.image = thumbnail;
    }];
    
    
    
    //    [self setupPlayer];
    //    [self.view addSubview:self.containerView];
    //    self.containerView.backgroundColor = UIColor.redColor;
    //    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.width.offset(width);
    //        make.centerX.offset(0);
    //        make.top.offset(KNavBarHight);
    //        make.bottom.inset(120 + TabbarSafeBottomMargin);
    //    }];
    //
    //    [self.view addSubview:self.playOrPauseBtn];
    //    [self.playOrPauseBtn addTarget:self action:@selector(playOrPause) forControlEvents:UIControlEventTouchUpInside];
    //    [self.playOrPauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.center.equalTo(self.containerView);
    //        make.width.height.offset(44);
    //    }];
    
    [self.tags enumerateObjectsUsingBlock:^(TJTemplateTagModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.width = [obj.text getStringSizeWithWidth:200 font:UIFontMake(12)].width + 16;
    }];
    
    UILabel *textLabel = [UILabel lableWithSuperView:self.containerView font:UIFontSemiboldMake(16) color:UIColor.whiteColor title:self.model.videoName textAlignment:NSTextAlignmentCenter];
    textLabel.numberOfLines = 0;
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(28);
        make.bottom.inset(12);
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(28);
        make.bottom.equalTo(textLabel.mas_top).inset(6);
        make.height.offset(18);
    }];
    
    TJStyle1Button *startButton = [TJStyle1Button buttonWithSuperView:self.view font:UIFontMediumMake(16) color:nil title:@"去使用"];
    [startButton addTarget:self action:@selector(didClickStartButton) forControlEvents:UIControlEventTouchUpInside];
    [startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.height.offset(buttonHeight);
        make.bottom.inset(TabbarSafeBottomMargin + 30);
    }];
    
    
}

- (void)setupPlayer {
    
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    playerManager.shouldAutoPlay = NO;
    
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.containerView];
    self.player.controlView = self.controlView;
    self.player.pauseWhenAppResignActive = NO;
    self.player.orientationDidChanged = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        
    };
    /// 播放完成
    TJWeakify(self)
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        [weakself.player seekToTime:0 completionHandler:^(BOOL finished) {
            [weakself.controlView.portraitControlView playBtnSelectedState:NO];
        }];
        weakself.playOrPauseBtn.alpha = 1;
        weakself.playOrPauseBtn.selected = NO;
    };
    
    
    [[TJVideoCoverDownloader shareDownLoader] downloadWithUrl:self.model.videoUrl completion:^(UIImage * _Nullable thumbnail) {
        self.coverImage = thumbnail;
        self.player.currentPlayerManager.view.coverImageView.image = self.coverImage;
    }];
    
    self.player.assetURL = [NSURL URLWithString:self.model.videoUrl];
    
}


- (void)tapPlayerView {
    TJVideoPlayController *videoPlayController = [[TJVideoPlayController alloc] init];
    videoPlayController.url = self.model.videoUrl;
    videoPlayController.coverImage = self.coverImage;
    [self presentViewController:videoPlayController animated:YES completion:nil];
}

- (void)didClickStartButton {
    
    TJUIAlertController *alert = [TJUIAlertController alertControllerWithTitle:nil message:nil preferredStyle:TJUIAlertControllerStyleAlert];
    [alert addAction:[TJUIAlertAction actionWithTitle:@"拍摄" style:TJUIAlertActionStyleDefault handler:^(TJUIAlertAction * _Nonnull action) {
        
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
            [self alertWithTitle:nil message:@"相机功能被关了，前往开启？" leftButtonName:@"取消" rightButtonName:@"前往开启".localizedString leftButtonBlock:^{
            } rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromCamera];
        
    }]];
    
    [alert addAction:[TJUIAlertAction actionWithTitle:@"本地相册" style:TJUIAlertActionStyleDefault handler:^(TJUIAlertAction * _Nonnull action) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
            [self alertWithTitle:nil message:@"不能访问您的相册，前往开启？".localizedString leftButtonName:@"取消" rightButtonName:@"前往开启".localizedString leftButtonBlock:^{
            } rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromPhotoAlbum];
    }]];
    
    [alert addAction:[TJUIAlertAction actionWithTitle:@"取消" style:TJUIAlertActionStyleCancel handler:^(TJUIAlertAction * _Nonnull action) {
        
    }]];
    
    [alert showInViewController:self];
}

- (void)chooseFromPhotoAlbum {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie];
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)chooseFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie];
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
        imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSURL *videoURL = info[UIImagePickerControllerMediaURL];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        
        
        TJTemplateEditController *templateEditController = [[TJTemplateEditController alloc] init];
        templateEditController.model = self.model;
        templateEditController.videoURL = videoURL;
        [self.navigationController pushViewController:templateEditController];
    }];
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        SDCollectionTagsFlowLayout *flowLayout= [[SDCollectionTagsFlowLayout alloc] initWthType:TagsTypeWithCenter];
        flowLayout.minimumLineSpacing = 2;
        flowLayout.minimumInteritemSpacing = 8;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = UIColor.clearColor;
        [_collectionView registerClass:TJTemplateTagCell.class forCellWithReuseIdentifier:@"TJTemplateTagCell"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.tags.count;
}

- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TJTemplateTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TJTemplateTagCell" forIndexPath:indexPath];
    cell.model = self.tags[indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    TJTemplateTagModel *model = self.tags[indexPath.row];
    return CGSizeMake(model.width, 18);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tags.count;
}

- (NSArray<TJTemplateTagModel *> *)tags {
    if (!_tags) {
        _tags = @[
            [TJTemplateTagModel modelWithBlock:^(TJTemplateTagModel * _Nonnull model) {
                model.text = self.model.dataDate;
            }],
            [TJTemplateTagModel modelWithBlock:^(TJTemplateTagModel * _Nonnull model) {
                model.text = [NSString stringWithFormat:@"%@人使用", self.model.usedTimes];
            }],
            [TJTemplateTagModel modelWithBlock:^(TJTemplateTagModel * _Nonnull model) {
                model.text = [NSString stringWithFormat:@"打卡%@天", self.model.clockTimes];
            }],
        ];
    }
    return _tags;
}

- (TJPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [TJPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 5;
        _controlView.autoFadeTimeInterval = 0.5;
        _controlView.prepareShowLoading = YES;
        _controlView.prepareShowControlView = NO;
        _controlView.showCustomStatusBar = YES;
        _controlView.effectViewShow = NO;
    }
    return _controlView;
}

- (UIButton *)playOrPauseBtn {
    if (!_playOrPauseBtn) {
        _playOrPauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playOrPauseBtn setImage:ZFPlayer_Image(@"new_allPlay_44x44_") forState:UIControlStateNormal];
        [_playOrPauseBtn setImage:ZFPlayer_Image(@"new_allPause_44x44_") forState:UIControlStateSelected];
    }
    return _playOrPauseBtn;
}

- (void)playOrPause {
    self.playOrPauseBtn.selected = !self.playOrPauseBtn.isSelected;
    if (self.playOrPauseBtn.isSelected) {
        self.playOrPauseBtn.hidden = YES;
        [self.player.currentPlayerManager play];
        [self.controlView.portraitControlView playBtnSelectedState:YES];
    } else {
        [self.player.currentPlayerManager pause];
    }
}

- (UIImageView *)containerView {
    if (!_containerView) {
        _containerView = [UIImageView new];
        _containerView.image = self.coverImage;
        _containerView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _containerView;
}


@end
